package com.fnst.common.facecomp.servlet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.zip.GZIPInputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fnst.common.facecomp.utils.Base64;
import com.fnst.common.facecomp.utils.Utils;

import sun.misc.BASE64Decoder;

/**
 * Servlet implementation class UploadImg
 */
public class UploadImgServlet extends AbstractDetectServlet {
	private static final long serialVersionUID = 1L;
	private static final int BUFFER_SIZE = 1024;
	
	protected Logger log = LoggerFactory.getLogger(getClass());
//	private CommonDao commonDao;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImgServlet() {
        super();
        try {
//			commonDao = CommonDao.getInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		log.info("=== upload ===");
		request.setCharacterEncoding("UTF-8");
		String returns = null;
		String imgBase64 = request.getParameter("imgBase64");
		Date d = new Date();
		
		if (imgBase64 == null || "".equals(imgBase64.trim())){
			log.info("imgBase64 is null");
			returns="imgIsNull";
		}else{
			log.info("imgBase64 size: " + imgBase64.length());
			
			imgBase64 = imgBase64.replaceAll(" ", "+");
			imgBase64 = ungzip(imgBase64);
			BASE64Decoder decoder = new BASE64Decoder();  
	        try   
	        {  
	            byte[] b = decoder.decodeBuffer(imgBase64);  
	            for(int i=0;i<b.length;++i)  
	            {  
	                if(b[i]<0)  
	                {
	                    b[i]+=256;  
	                }  
	            }
	    		
	    		String daySuffix = Utils.getDateString(new Date()) + "/";
	    		
	    		String imgName = d.getTime() + ".jpg";
	    		log.info("imgName: " + imgName);
	            
	            String imgFilePath = getUploadPath(daySuffix) + imgName;  
	            OutputStream out = new FileOutputStream(imgFilePath);      
	            out.write(b);
	            out.flush();
	            out.close();
	            returns="ok&" + daySuffix + imgName;
	        }catch (Exception e){  
	        	log.error("UploadImg error", e);
	            returns="uploadsErr";
	        }  
			
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(returns);
		pw.flush();
		pw.close();
		
		
	}
	
	public String ungzip(String str) throws IOException { 
        if (str == null || str.length() == 0) { 
            return null; 
        } 
               
            byte[] decode = Base64.decode(str); 
               
            ByteArrayInputStream bais = new ByteArrayInputStream(decode); 
            GZIPInputStream gzip = new GZIPInputStream(bais); 
   
            byte[] buf = new byte[BUFFER_SIZE]; 
            int len = 0; 
               
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
            int t = 0;
			while((len=gzip.read(buf, 0, BUFFER_SIZE))>=0){
				for (int i = 0; i< buf.length; i++) {
            		if (buf[i] < 0) {
            			buf[i] += 256;
            		}
            	}
				baos.write(buf, 0, len);
				t += len;
			} 
            gzip.close(); 
            baos.flush(); 
               
            decode = baos.toByteArray();
               
            baos.close(); 
   
            return new String(decode, "UTF-8"); 
   
    }  
	
}
